package com.wp.service;

import com.wp.dao.GoodsDao;
import com.wp.entity.Goods;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author: WangPeng
 * @createTime: 2022/12/08 11:14
 * @description:
 * @version: v1.0
 */
@Service
public class GoodsStockService04_redisson {

    @Autowired
    private GoodsDao goodsDao;

    @Autowired
    private RedissonClient redisson;

    public String decrement(Integer id) {
        //获取锁对象
        RLock lock = redisson.getLock("goods::" + id);
        lock.lock(30, TimeUnit.SECONDS);
        try {
            //1. 查找指定商品的库存
            Goods goods = goodsDao.selectById(id);
            //2. 判断库存数是否大于0
            if (goods.getNumber() > 0) {
                //3.减库存
                goods.setNumber(goods.getNumber() - 1);
                int i = goodsDao.updateById(goods);
                System.out.println("商品编号为:" + id + "的商品库存剩余:" + goods.getNumber() + "个");
                return "商品编号为:" + id + "的商品库存剩余:" + goods.getNumber() + "个";
            } else {
                System.out.println("商品编号为:" + id + "的商品库存不足。");
                return "商品编号为:" + id + "的商品库存不足。";
            }
        } finally {
            //释放锁
            lock.unlock();
        }
    }
}
